<?php
class MSEP_Misc extends MSEP_Object
{


      private $cmds;



      public function __init(MSEP $core)
      {
            $this->core = $core;
      }



      public function total_comments($object_id)
      {
            $query = $this->core->_('database')->fetch_assoc($this->core->_('database')->query("SELECT count({$this->core->__('plugin')}comment_id) as total_comments FROM se_{$this->core->__('plugin')}comments WHERE {$this->core->__('plugin')}comment_{$this->core->__('plugin')}_id = '{$object_id}'"));

            return $query["total_comments"];
      }



      public function privacy_options($opts, $postfix = "")
      {
            $return = array();

            foreach ($opts as $opt)
            {
                  if (substr($opt, -1) == "s")
                  {
                        $plural = $opt;
                        $singular = substr($opt, 0, -1);
                  }
                  else
                  {
                        $plural = $opt;
                        $singular = $opt;
                  }

                  ${"level_{$this->core->__('plugin')}_{$plural}{$postfix}"} = unserialize($this->core->__('user')->level_info["level_{$this->core->__('plugin')}_{$plural}{$postfix}"]);
                  rsort(${"level_{$this->core->__('plugin')}_{$plural}{$postfix}"});

                  for ($c=0;$c<count(${"level_{$this->core->__('plugin')}_{$plural}{$postfix}"});$c++)
                  {
                        if (${"level_{$this->core->__('plugin')}_{$plural}{$postfix}"}[$c] == -1)
                        {
                              //SE_Language::_preload(60100046);
                              ${"{$singular}_options{$postfix}"}[${"level_{$this->core->__('plugin')}_{$plural}{$postfix}"}[$c]] = 60100046;
                        }
                        elseif (user_privacy_levels(${"level_{$this->core->__('plugin')}_{$plural}{$postfix}"}[$c]) != "")
                        {
                              SE_Language::_preload(user_privacy_levels(${"level_{$this->core->__('plugin')}_{$plural}{$postfix}"}[$c]));
                              ${"{$singular}_options{$postfix}"}[${"level_{$this->core->__('plugin')}_{$plural}{$postfix}"}[$c]] = user_privacy_levels(${"level_{$this->core->__('plugin')}_{$plural}{$postfix}"}[$c]);
                        }
                  }

                  $this->core->__('smarty')->assign("{$singular}_options{$postfix}", ${"{$singular}_options{$postfix}"});

                  $return[$plural] = ${"level_{$this->core->__('plugin')}_{$plural}{$postfix}"};
            }

            return $return;
      }



      public function create_category($title)
      {
            $languagevar_id = SE_Language::edit(0, $title);

            $sql = "INSERT INTO se_{$this->core->__('plugin')}cats ({$this->core->__('plugin')}cat_languagevar_id) VALUES ('{$languagevar_id}')";
            $resource = $this->core->_('database')->query($sql);

            if($this->core->_('database')->affected_rows($resource) != -1)
            {
                  echo '{"result" : "success", "cat_id" : '.$this->core->_('database')->insert_id().', "cat_languagevar_id" : '.$languagevar_id.'}';
            }
            else
            {
                  echo '{"result" : "failure"}';
            }

            exit;
      }



      public function delete_category($id)
      {
            $sql = "DELETE FROM se_{$this->core->__('plugin')}cats WHERE {$this->core->__('plugin')}cat_id = '{$id}' LIMIT 1";
            $resource = $this->core->_('database')->query($sql);

            $sql = "UPDATE se_{$this->core->__('plugin')}s SET {$this->core->__('plugin')}_cat = '1' WHERE {$this->core->__('plugin')}_cat = '{$id}'";
            $resource = $this->core->_('database')->query($sql);

            if($this->core->_('database')->affected_rows($resource) != -1)
            {
                  echo '{"result" : "success"}';
            }
            else
            {
                  echo '{"result" : "failure"}';
            }

            exit;
      }



      public function edit_category($id, $title)
      {
            $sql = "SELECT * FROM se_{$this->core->__('plugin')}cats WHERE {$this->core->__('plugin')}cat_id = '{$id}' LIMIT 1";
            $resource = $this->core->_('database')->query($sql);

            if (!$this->core->_('database')->num_rows($resource) != -1)
            {
                  echo '{"result" : "failure"}';
                  exit;
            }

            $result = $this->core->_('database')->fetch_assoc($resource);
            $languagevar_id = $result["{$this->core->__('plugin')}cat_languagevar_id"];

            $languagevar_id = SE_Language::edit($languagevar_id, $title);

            if(!empty($languagevar_id))
            {
                  echo '{"result" : "success"}';
            }
            else
            {
                  echo '{"result" : "failure"}';
            }

            exit;
      }



      public function tag_cloud($what = "object")
      {
            $sql = "SELECT * FROM se_{$this->core->__('plugin')}tags ORDER BY value DESC LIMIT 0, 50";
            $result = $this->core->_('database')->query($sql);

            if ($this->core->_('database')->affected_rows($result) != 0)
            {
                  $tag_cloud = array();

                  while ($row = $this->core->_('database')->fetch_array($result))
                  {
                        $tag_cloud[$row['tag']] = $row['value'];
                  }

                 $tags = $tag_cloud;
            }

            arsort($tags);

            $max_size = 32;
            $min_size = 12;

            $max_qty = max(array_values($tags));
            $min_qty = min(array_values($tags));

            $spread = $max_qty - $min_qty;

            if ($spread == 0)
            {
                  $spread = 1;
            }

            $step = ($max_size - $min_size) / ($spread);

            foreach ($tags as $key => $value)
            {
                  $size = round($min_size + (($value - $min_qty) * $step));
                  $cloud[] = "<a href='browse_{$this->core->__('plugin')}s.php?q={$key}&type=tag' style='font-size: {$size}px' title='".SE_Language::get('60000004', array($value, $what, $key))."'>{$key}</a>";
            }

            shuffle($cloud);

            return $cloud;
      }



      public function real_escape()
      {
            $numargs = func_num_args();
            $data = array();

            for ($i = 0; $i < $numargs; $i++)
            {
                  $data[] = $this->core->_('database')->real_escape_string(func_get_arg($i));
            }

            return $data;
      }



      public function decode_entities()
      {
            $numargs = func_num_args();
            $data = array();

            for ($i = 0; $i < $numargs; $i++)
            {
                  $data[] = $this->_decode_entities_full(func_get_arg($i));
            }

            return $data;
      }


      private function _decode_entities_full($string, $quotes = ENT_QUOTES, $charset = 'UTF-8')
      {
            return html_entity_decode(preg_replace_callback('/&([a-zA-Z][a-zA-Z0-9]+);/', '_convert_entity', $string), $quotes, $charset);
      }



      private function _convert_entity($matches, $destroy = true)
      {
            $table = array('quot' => '&#34;','amp' => '&#38;','lt' => '&#60;','gt' => '&#62;','OElig' => '&#338;','oelig' => '&#339;','Scaron' => '&#352;','scaron' => '&#353;','Yuml' => '&#376;','circ' => '&#710;','tilde' => '&#732;','ensp' => '&#8194;','emsp' => '&#8195;','thinsp' => '&#8201;','zwnj' => '&#8204;','zwj' => '&#8205;','lrm' => '&#8206;','rlm' => '&#8207;','ndash' => '&#8211;','mdash' => '&#8212;','lsquo' => '&#8216;','rsquo' => '&#8217;','sbquo' => '&#8218;','ldquo' => '&#8220;','rdquo' => '&#8221;','bdquo' => '&#8222;','dagger' => '&#8224;','Dagger' => '&#8225;','permil' => '&#8240;','lsaquo' => '&#8249;','rsaquo' => '&#8250;','euro' => '&#8364;','fnof' => '&#402;','Alpha' => '&#913;','Beta' => '&#914;','Gamma' => '&#915;','Delta' => '&#916;','Epsilon' => '&#917;','Zeta' => '&#918;','Eta' => '&#919;','Theta' => '&#920;','Iota' => '&#921;','Kappa' => '&#922;','Lambda' => '&#923;','Mu' => '&#924;','Nu' => '&#925;','Xi' => '&#926;','Omicron' => '&#927;','Pi' => '&#928;','Rho' => '&#929;','Sigma' => '&#931;','Tau' => '&#932;','Upsilon' => '&#933;','Phi' => '&#934;','Chi' => '&#935;','Psi' => '&#936;','Omega' => '&#937;','alpha' => '&#945;','beta' => '&#946;','gamma' => '&#947;','delta' => '&#948;','epsilon' => '&#949;','zeta' => '&#950;','eta' => '&#951;','theta' => '&#952;','iota' => '&#953;','kappa' => '&#954;','lambda' => '&#955;','mu' => '&#956;','nu' => '&#957;','xi' => '&#958;','omicron' => '&#959;','pi' => '&#960;','rho' => '&#961;','sigmaf' => '&#962;','sigma' => '&#963;','tau' => '&#964;','upsilon' => '&#965;','phi' => '&#966;','chi' => '&#967;','psi' => '&#968;','omega' => '&#969;','thetasym' => '&#977;','upsih' => '&#978;','piv' => '&#982;','bull' => '&#8226;','hellip' => '&#8230;','prime' => '&#8242;','Prime' => '&#8243;','oline' => '&#8254;','frasl' => '&#8260;','weierp' => '&#8472;','image' => '&#8465;','real' => '&#8476;','trade' => '&#8482;','alefsym' => '&#8501;','larr' => '&#8592;','uarr' => '&#8593;','rarr' => '&#8594;','darr' => '&#8595;','harr' => '&#8596;','crarr' => '&#8629;','lArr' => '&#8656;','uArr' => '&#8657;','rArr' => '&#8658;','dArr' => '&#8659;','hArr' => '&#8660;','forall' => '&#8704;','part' => '&#8706;','exist' => '&#8707;','empty' => '&#8709;','nabla' => '&#8711;','isin' => '&#8712;','notin' => '&#8713;','ni' => '&#8715;','prod' => '&#8719;','sum' => '&#8721;','minus' => '&#8722;','lowast' => '&#8727;','radic' => '&#8730;','prop' => '&#8733;','infin' => '&#8734;','ang' => '&#8736;','and' => '&#8743;','or' => '&#8744;','cap' => '&#8745;','cup' => '&#8746;','int' => '&#8747;','there4' => '&#8756;','sim' => '&#8764;','cong' => '&#8773;','asymp' => '&#8776;','ne' => '&#8800;','equiv' => '&#8801;','le' => '&#8804;','ge' => '&#8805;','sub' => '&#8834;','sup' => '&#8835;','nsub' => '&#8836;','sube' => '&#8838;','supe' => '&#8839;','oplus' => '&#8853;','otimes' => '&#8855;','perp' => '&#8869;','sdot' => '&#8901;','lceil' => '&#8968;','rceil' => '&#8969;','lfloor' => '&#8970;','rfloor' => '&#8971;','lang' => '&#9001;','rang' => '&#9002;','loz' => '&#9674;','spades' => '&#9824;','clubs' => '&#9827;','hearts' => '&#9829;','diams' => '&#9830;','nbsp' => '&#160;','iexcl' => '&#161;','cent' => '&#162;','pound' => '&#163;','curren' => '&#164;','yen' => '&#165;','brvbar' => '&#166;','sect' => '&#167;','uml' => '&#168;','copy' => '&#169;','ordf' => '&#170;','laquo' => '&#171;','not' => '&#172;','shy' => '&#173;','reg' => '&#174;','macr' => '&#175;','deg' => '&#176;','plusmn' => '&#177;','sup2' => '&#178;','sup3' => '&#179;','acute' => '&#180;','micro' => '&#181;','para' => '&#182;','middot' => '&#183;','cedil' => '&#184;','sup1' => '&#185;','ordm' => '&#186;','raquo' => '&#187;','frac14' => '&#188;','frac12' => '&#189;','frac34' => '&#190;','iquest' => '&#191;','Agrave' => '&#192;','Aacute' => '&#193;','Acirc' => '&#194;','Atilde' => '&#195;','Auml' => '&#196;','Aring' => '&#197;','AElig' => '&#198;','Ccedil' => '&#199;','Egrave' => '&#200;','Eacute' => '&#201;','Ecirc' => '&#202;','Euml' => '&#203;','Igrave' => '&#204;','Iacute' => '&#205;','Icirc' => '&#206;','Iuml' => '&#207;','ETH' => '&#208;','Ntilde' => '&#209;','Ograve' => '&#210;','Oacute' => '&#211;','Ocirc' => '&#212;','Otilde' => '&#213;','Ouml' => '&#214;','times' => '&#215;','Oslash' => '&#216;','Ugrave' => '&#217;','Uacute' => '&#218;','Ucirc' => '&#219;','Uuml' => '&#220;','Yacute' => '&#221;','THORN' => '&#222;','szlig' => '&#223;','agrave' => '&#224;','aacute' => '&#225;','acirc' => '&#226;','atilde' => '&#227;','auml' => '&#228;','aring' => '&#229;','aelig' => '&#230;','ccedil' => '&#231;','egrave' => '&#232;','eacute' => '&#233;','ecirc' => '&#234;','euml' => '&#235;','igrave' => '&#236;','iacute' => '&#237;','icirc' => '&#238;','iuml' => '&#239;','eth' => '&#240;','ntilde' => '&#241;','ograve' => '&#242;','oacute' => '&#243;','ocirc' => '&#244;','otilde' => '&#245;','ouml' => '&#246;','divide' => '&#247;','oslash' => '&#248;','ugrave' => '&#249;','uacute' => '&#250;','ucirc' => '&#251;','uuml' => '&#252;','yacute' => '&#253;','thorn' => '&#254;','yuml' => '&#255;');

            if (isset($table[$matches[1]]))
            {
                  return $table[$matches[1]];
            }

            return $destroy ? '' : $matches[0];
      }



      public function whereis($what)
      {
            $path_str = trim(str_replace("{$what}:", "", exec("whereis {$what}")));
            $paths_array = explode(" ", $path_str);

            $paths = array();

            foreach ($paths_array as $path)
            {
                  $dirs = explode("/", $path);
                  $last = count($dirs)-1;

                  if (!strpos($dirs[$last], "."))
                  {
                        $paths[] = $path;
                  }
            }

            return $paths;
      }



      public function which($what)
      {
            $paths = array();
            $paths[] = exec("which {$what}");

            return $paths;
      }



      public function locate($what)
      {
            exec("locate '*/{$what}'", $paths);

            return $paths;
      }



      public function test_path($path, $what)
      {
            exec("{$path} {$this->core->cmds[$what]}", $result);

            if (!empty($result) && preg_match("/$what/i", $result[0]))
            {
                  return $path;
            }

            return false;
      }



      public function choose_path($what)
      {
            /*foreach ($this->core->possible_paths[$what] as $path)
            {
                  if (($p = $this->test_path($path, $what)) !== false)
                  {
                        return array($p, true);
                  }
            }*/

            $paths = $this->whereis($what);

            if (!empty($paths) && !empty($what))
            {
                  foreach ($paths as $path)
                  {
                        exec("{$path} {$this->core->cmds[$what]}", $result);

                        if (!empty($result) && preg_match("/$what/i", $result[0]))
                        {
                              return array($path, true);
                        }
                  }
            }
            else
            {
                  return "";
            }

            foreach ($paths as $path)
            {
                  if (in_array($path, $this->core->possible_paths[$what]))
                  {
                        return array($path, false);
                  }
            }
      }



      public function user_dir($user_id = 0, $plugin)
      {
            if (empty($plugin))
            {
                  $plugin = $this->core->__('plugin');
            }

            $subdir = $user_id+999-(($user_id-1)%1000);
            $dir = "./uploads_{$plugin}/{$subdir}/{$user_id}/";

            return $dir;
      }



      public function swf_vars()
      {
            $_SESSION["flash"] = $_SERVER["HTTP_HOST"];
            $_SESSION["url_base"] = $url->url_base;
      }



      public function js_vars()
      {
            $_SESSION["js"] = $_SERVER["HTTP_HOST"];
            $_SESSION["url_base"] = $url->url_base;
      }



      private function quote_callback($matches)
      {
            if (!preg_match("/\"/", $matches[1])) return "\"{$matches[1]}\"";
            else return "{$matches[1]}";
      }



      public function quote($string)
      {
            if (is_array($string))
            {
                  $string = implode(",", $string);
            }

            $string_new = preg_replace("/^([a-z0-9\|]+)$/", '"$1"', $string);

            if ($string == $string_new)
            {
                  $string_new = preg_replace("/(.*?)([a-z0-9\|]+)$/", '$1"$2"', $string_new);
            }

            $string_new = preg_replace("/^([a-z0-9\|]+)(.*?)$/", '"$1"$2', $string_new);

            $string = preg_replace_callback('/([^,]+)/', array(get_class($this), "quote_callback"), $string_new);

            return $string;
      }



      public function unquote($string)
      {
            return explode(",", str_replace("\"", "", str_replace("\"", "", $string)));
      }



      function unlink($str, $remove_dir = true, $no_index = false)
      {
            if (!is_dir($str))
            {
                  if (is_writable($str))
                  {
                        return @unlink($str);
                  }
                  else
                  {
                        $this->core->_('messages')->failure(FILE_NOT_DEL);
                  }
            }
            elseif (is_dir($str))
            {
                  $scan = glob(rtrim($str,'/').'/*');

                  foreach($scan as $index => $path)
                  {
                        if (!$no_index || ($no_index && !preg_match("/(.*?)index.php(.*?)/", $path)))
                        {
                              $this->unlink($path);
                        }
                  }

                  if ($remove_dir && is_writable($str))
                  {
                        if (is_writable($str))
                        {
                              @rmdir($str);
                        }
                        else
                        {
                              $this->core->_('messages')->failure(DIR_NOT_DEL);
                        }
                  }

                  if ($this->core->_('messages')->error == 0)
                  {
                        return true;
                  }

                  return false;
            }
      }


}
?>